import json
from datetime import datetime,timedelta

import jwt
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from lianxi20250916.models import user


# Create your views here.
@csrf_exempt
def login(request):
    # 用户名密码是否为空
    data=json.loads(request.body)
    if data['username']=='' or data['password']=='':
        return JsonResponse(
            {
                'msg':'密码或用户名为空'
            }
        )
    # 账号不存在
    if user.objects.filter(username=data['username']).exists()==False:
        return JsonResponse(
            {
                'msg':'用户不存在'
            }
        )
    # 密码错误
    u=user.objects.get(username=data['username'])
    if u.password!=data['password']:
        return JsonResponse(
            {
                'msg':'密码错误'
            }
        )
    mi='123456'
    t=datetime.now()+timedelta(minutes=5)
    pay={
        'userid':u.userid,
        'username':u.username,
        'password':u.password,
        'exp':int(t.timestamp()),
        'name':'赵广安是一条'
    }
    token=jwt.encode(pay,mi)
    return JsonResponse(
        {
            'msg':'登录成功',
            'token':token
        }
    )